package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Region;
import cn.wolfcode.luowowo.query.RegionQuery;
import cn.wolfcode.luowowo.repository.RegionRepository;
import cn.wolfcode.luowowo.service.IRegionService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.querydsl.QuerydslUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionRepository regionRepository;

    @Autowired
    private MongoTemplate template;
    @Override
    public void save(Region region) {
        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }


    @Override
    public Region get(String id) {
        Optional<Region> optional = regionRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

    @Override
    public List<Region> list() {
        return regionRepository.findAll();
    }

    @Override
    public Page<Region> query(RegionQuery qo) {
        //先查询出所有的地区数据，然后对它进行分页
        //1  创造出查询条件对象，然后得到分页对象，最后得到页面结果集对象
        Query query = new Query();
        //创建分页模板(包含排序规则)
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template,Region.class,query,pageable);
    }


    @Override
    public void saveOrUpdate(Region region) {
        //如果传过来的对象有id，说明是更新操作
        //否则是保存操作  mongodb更新是全量更新，就是所有的属性都会更新
        //为了解决这个问题，必须先查询出要更新的对象  新增的时候id不为空，为空字符串，所以
        //改为判断字符串长度
        if(StringUtils.hasLength(region.getId())){
            Region reg= template.findById(region.getId(), Region.class);
            regionRepository.save(reg);
        }else{
            //添加时为了id不为空，将它设为null
            region.setId(null);
            regionRepository.save(region);
        }
    }


    @Override
    public void changeHotValue(String id, int hot) {
        //通过id查出要修改热门状态的地区对象，然后设置是否热门，最后做更新操作
       Region region = template.findById(id,Region.class);
       region.setIshot(hot);
       regionRepository.save(region);
    }

    @Override
    public List<Region> queryHotRegion() {
        return regionRepository.findByIshotOrderBySequenceAsc(Region.STATE_HOT);
    }

}
